#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tornado.web import RequestHandler
import pymongo
import re
import render
import codecs
from _base import BaseHandler
import datetime
import sys
sys.path.insert(0,'/home/leeray/workspaces/Python/wanalytics/')
sys.path.insert(0,'/opt/web/')
from Tools import getPid
from Tools import connectMySQL 
import json
from util import cache, settings
import _clientCache as clientcache
import logging
import socket, sys
#import pyrad.packet
#from pyrad.client import Client
#from pyrad.dictionary import Dictionary

class UserLogin(BaseHandler):    
    def get(self):
        _uname = self.get_argument('uname', '').strip() or ''
        _pwd = self.get_argument('pwd','').strip() or ''
        
        resjson = UserCheck().check(_uname, _pwd)

        self.write(resjson)
        self.finish()

class UserCheck():
    def check(self, _uname, _pwd):
        """
        resjson = {"status": "failed", "code": 0}
        if  _uname and _pwd:
            srv=Client(server="10.10.0.253", secret="VxvJW3gG", dict=Dictionary("dictionary"))

            req=srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=_uname)
            req["NAS-IP-Address"]     = "10.103.13.15"
            req["NAS-Port"]           = 0
            req["Service-Type"]       = "Login-User"
            req["NAS-Identifier"]     = "trillian"
            req["Called-Station-Id"]  = "00-04-5F-00-0F-D1"
            req["Calling-Station-Id"] = "00-01-24-80-B3-9C"
            req["Framed-IP-Address"]  = "10.10.0.253"
            req["User-Password"]      = req.PwCrypt(_pwd)
 
            isSucc = False
            try:
                reply=srv.SendPacket(req)
            except pyrad.client.Timeout:
                print "RADIUS server does not reply"
            except socket.error, error:
                print "Network error: " + error[1]
            if reply.code==pyrad.packet.AccessAccept:
                isSucc = True
            else:
                pass

            if isSucc == True:
                db = connectMySQL.connMySQL_stat()
                c=db.cursor()
                sql = 'select id, fid, type from stat_user where username="{0}"'.format(_uname)
                logging.info(sql)
                c.execute(sql)  
                res= c.fetchall()
                if res and res[0][0] > 0:
                    resjson = {"status": "success","code": 1,"results": {"userid": res[0][1],"username": _uname, "type": res[0][2]}}
            
                c.close()
                db.close()
        """
        resjson = {"status": "success","code": 1,"results": {"userid": "123","username": "liuyue", "type": "0"}}    
        return resjson
